package com.sls.api.game.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.parser.ReadJieyitongConfig;
import com.sls.api.game.pojo.JieyitongOrderStatusInfo;
import com.sls.api.util.IpUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @description 捷易通订单结果异步通知
 * @author Wangxuegang
 * @date 2013-3-30
 */
public class JieyitongOrderStatusServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger
			.getLogger(JieyitongOrderStatusServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 商户编号
		String userid = req.getParameter("userid");
		// 商户订单号
		String requestid = req.getParameter("requestid");
		// 直充结果编码
		String resultno = req.getParameter("resultno");
		// 验证摘要串
		String vstr = req.getParameter("vstr");
		log.info("捷易通异步推送的订单消息内容：" + "\n商户编号:" + userid + "\n商户订单号:"
				+ requestid + "\n直充结果编码:" + resultno + "\n验证摘要串:" + vstr);
		boolean flag = checkdata(userid, requestid, resultno, vstr, resp);
		if (flag) {
			try {
				Gson gson = CommonUtil.gson();
				SocketDTO socketDTO = sendMessage(userid, requestid, resultno,
						req);
				Head head = socketDTO.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();

				String bodyStr = socketDTO.getBody();
				String resBodyStr = gson.fromJson(bodyStr, String.class);
				String result = ResponseDataXmlFormat
						.assembleXmlStrAboutJieyitong(resBodyStr, resCode,
								resMsg);
				resp.getWriter().write(result);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (Exception e) {
				log.error("出错", e);
				resp.getWriter().write("其他错误");
				resp.getWriter().flush();
				resp.getWriter().close();
			}
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * 数据校验
	 * 
	 * @param userid
	 * @param requestid
	 * @param resultno
	 * @return
	 * @throws IOException
	 */
	private boolean checkdata(String userid, String requestid, String resultno,
			String vstr, HttpServletResponse resp) throws IOException {
		boolean flag = false;
		if (userid == null || "".equals(userid)) {
			ResponseDataXmlFormat.returnResMsgOfUTF8("101", "缺少必需参数[userid]",
					resp);
		} else if (requestid == null || "".equals(requestid)) {
			ResponseDataXmlFormat.returnResMsgOfUTF8("101",
					"缺少必需参数[requestid]", resp);
		} else if (resultno == null || "".equals(resultno)) {
			ResponseDataXmlFormat.returnResMsgOfUTF8("101", "缺少必需参数[resultno]",
					resp);
		} else if (vstr == null || "".equals(vstr)) {
			ResponseDataXmlFormat.returnResMsgOfUTF8("101", "缺少必需参数[vstr]",
					resp);
		} else {
			JieyitongOrderStatusInfo info = null;
			String secretkey = null;
			info = ReadJieyitongConfig.readConfig();
			if (info != null) {
				secretkey = info.getSecretkey().trim();
			}
			StringBuilder strBui = new StringBuilder();
			strBui.append(userid);
			strBui.append("^");
			strBui.append(requestid);
			strBui.append("^");
			strBui.append(resultno);
			strBui.append("^");
			strBui.append(secretkey);
			String data = strBui.toString().trim();
			String vstrValue = UtilMD5Encryption.createMD5Encryption(data);
			if (vstrValue.equals(vstr)) {
				flag = true;
			} else {
				String xmlStr = "签名失败";
				resp.getWriter().write(xmlStr);
				resp.getWriter().flush();
				resp.getWriter().close();
			}
		}

		return flag;
	}

	/**
	 * 消息发送
	 * 
	 * @param userid
	 * @param requestid
	 * @param resultno
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(String userid, String requestid,
			String resultno, HttpServletRequest req) {
		JieyitongOrderStatusInfo info = new JieyitongOrderStatusInfo();
		info.setUserid(userid);
		info.setRequestid(requestid);
		info.setResultno(resultno);

		SocketDTO socketChangeVo = new SocketDTO();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("020950");//
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("0"); //
		socketChangeVo.setHead(head); // 报文头部
		return super.send(head, info);
	}

}
